package org.truenewx.tnxjeex.unit.repo.mybatis.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.truenewx.tnxjee.core.util.ClassUtil;
import org.truenewx.tnxjeex.unit.model.MeasureUnit;
import org.truenewx.tnxjeex.unit.support.MeasureUnits;

public abstract class AbstractMeasureUnitTypeHandler<T extends MeasureUnit<?>> extends BaseTypeHandler<T> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, parameter.getValue());
    }

    protected Class<T> getUnitClass() {
        return ClassUtil.getActualGenericType(getClass(), 0);
    }

    protected T parse(String value) {
        return MeasureUnits.getInstance().fromValue(getUnitClass(), value);
    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName) throws SQLException {
        if (rs.wasNull()) {
            return null;
        }
        String value = rs.getString(columnName);
        return parse(value);
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        if (rs.wasNull()) {
            return null;
        }
        String value = rs.getString(columnIndex);
        return parse(value);
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        if (cs.wasNull()) {
            return null;
        }
        String value = cs.getString(columnIndex);
        return parse(value);
    }

}
